import oss2
from itertools import islice
from dotenv import load_dotenv
import json
import os

# 加载 .env 文件
load_dotenv()


# 用于删除未用到的图片
input_json = "nest-workout.motions.json"
image_folder_min = "images/motions/min" 
image_folder_self = "images/motions/self" 
target_dirs = ["images/motions/min", "images/motions/self"]  # 指定目标目录列表

# 初始化OSS客户端
auth = oss2.Auth(os.getenv("ACCESS_KEY"), os.getenv("ACCESS_KEY_SECRET"))
bucket = oss2.Bucket(auth, os.getenv("Bucket_URL"), os.getenv('BUCKET_NAME'))

db_keys = set()

# 将数据库的文件列入
data = [
  '1747923959448_tmp_0139911fecc99cf59a55bb8042d74a1b901f9a75f9c9d1b3.jpg',
  '1747924150346_tmp_10a21c3d9d9fccc8e366204d1110dd369efcf2e8cb49c0b1.jpg',
  'Bulgarian-split-squat.png',
  'Double-dumbbell-pullover.png',
  'Dumbbell-hammer-curl-to-dumbbell-reverse-curl.png',
  'EZ-bar-wide-grip-upright-row.png',
  'High-front-plank.png',
  'Kettlebell-deadlift.png',
  'Kettlebell-lateral-raise.png',
  'Kneeling-plank.png',
  'Seated-alternating-knee-tuck.png',
  'Standing-dumbbell-overhead-triceps-extension.png',
  'Two-arm-supinated-dumbbell-curl.png',
  'Bulgarian-split-squat.png',
  'Double-dumbbell-pullover.png',
  'Dumbbell-hammer-curl-to-dumbbell-reverse-curl.png',
  'EZ-bar-wide-grip-upright-row.png',
  'High-front-plank.png',
  'Kettlebell-deadlift.png',
  'Kettlebell-lateral-raise.png',
  'Kneeling-plank.png',
  'Seated-alternating-knee-tuck.png',
  'Standing-dumbbell-overhead-triceps-extension.png',
  'Two-arm-supinated-dumbbell-curl.png'
]

for item in data:
    filename = item.strip()
    print(filename)
    # 跳过空文件名
    if not filename:
        continue
    
    for dir_path in target_dirs:
        db_keys.add(os.path.join(dir_path, filename).replace('\\', '/'))

    

# 步骤2: 获取OSS全量文件列表
oss_keys = []
for target_dir in target_dirs:
    for obj in oss2.ObjectIterator(bucket, prefix=target_dir + '/'):  # 添加斜杠确保精确匹配目录
        if not obj.key.endswith('/'):
            oss_keys.append(obj.key)
        




# 步骤3: 计算待删除Key列表
to_delete = [k for k in oss_keys if k not in db_keys]

print(f"dele: {to_delete}")

# 步骤4: 分批次删除（每次最多1000个）
batch_size = 1000
for i in range(0, len(to_delete), batch_size):
    batch = to_delete[i:i+batch_size]
    try:
        result = bucket.batch_delete_objects(batch)
        print(f"成功删除 {len(result)} 个文件")
        if result.errors:
            print(f"部分删除失败: {result.errors}")
    except oss2.exceptions.OssError as e:
        print(f"批量删除异常: {e}")